import 'package:dailoz/dio/http_util.dart';
import 'package:dailoz/response_json_entity.dart';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HomePageViewModel extends ChangeNotifier {
  List<dynamic> _todayTaskList = [];
  List<dynamic> _statusTaskList = [];

  bool? _isLoading = false;

  String? _userName = "";

  List<dynamic> get todayTaskList {
    return _todayTaskList;
  }

  List<dynamic> get statusTaskList {
    return _statusTaskList;
  }

  bool? get isLoading {
    return _isLoading;
  }

  String? get userName {
    return _userName;
  }

  Future<void> fetchTodayTaskList() async {
    _todayTaskList.clear();
    _isLoading = true;
    final prefs = await SharedPreferences.getInstance();
    try {
      Map<String, dynamic> response = await HttpUtil().get("/task/todayTask",
          data: {"id": prefs.getString("user-id"), "options": DateTime.now()});
      ResponseJsonEntity responseJsonEntity =
          ResponseJsonEntity.fromJson(response);
      if (responseJsonEntity.code == 200) {
        if (responseJsonEntity.data != null) {
          _todayTaskList = responseJsonEntity.data;
        }
      }
    } catch (e) {
      print(e);
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> fetchStatusTask() async {
    _statusTaskList.clear();
    final prefs = await SharedPreferences.getInstance();
    _isLoading = true;
    try {
      Map<String, dynamic> response = await HttpUtil()
          .get("/task/statusTask", data: {"id": prefs.getString("user-id")});
      ResponseJsonEntity responseJsonEntity =
          ResponseJsonEntity.fromJson(response);
      if (responseJsonEntity.code == 200) {
        if (responseJsonEntity.data != null) {
          _statusTaskList = responseJsonEntity.data;
        }
      }
    } catch (e) {
      print(e);
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> fetchUserName() async {
    final prefs = await SharedPreferences.getInstance();
    _userName = prefs.getString("user-name");
    notifyListeners();
  }

  void refresh() {
    fetchTodayTaskList();
    fetchStatusTask();
    notifyListeners();
  }
}
